﻿using AutoMapper;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using CommunityToolkit.Mvvm.Messaging;
using CommunityToolkit.Mvvm.Messaging.Messages;
using HandyControl.Controls;
using Microsoft.Extensions.Logging;
using ShanNiang.Hosting.Enumerate;
using ShanNiang.Service;
using ShanNiang.Service.Constants;
using ShanNiang.Service.Interfaces;
using ShanNiang.Service.LoginModels.Requests;
using System.Windows.Threading;

namespace ShanNiang.Mvvm.ViewModels
{
    /// <summary>
    /// 绑定页面的视图对象
    /// </summary>
    public partial class BindViewModel : UIViewModel
    {
        private readonly IIdsService _idsService;
        private readonly UserContext _userContext;

        private DispatcherTimer _timer;

        //private DispatcherTimer _timer;
        public BindViewModel(IIdsService idsService, UserContext userContext,
            IMapper mapper, ILogger<BindViewModel> logger) : base(mapper, logger)
        {
            _idsService = idsService;
            _userContext = userContext;


            _timer = new DispatcherTimer();
            _timer.Interval = TimeSpan.FromSeconds(1);
            _timer.Tick += Timer_Tick;

        }
        [ObservableProperty]
        private string? _phoneNumber;
        [ObservableProperty]
        private string? _smsCode;
        [ObservableProperty]
        [NotifyPropertyChangedFor(nameof(SendSmsButtonText))]
        private bool _waitingSms;
        [ObservableProperty]
        private string? _loginKey;
        [ObservableProperty]
        [NotifyPropertyChangedFor(nameof(SendSmsButtonText))]
        private int _waitSeconds;

        public string SendSmsButtonText
        {
            get
            {
                if (WaitingSms)
                {
                    return $"{WaitSeconds:D2}秒";
                }
                else
                {
                    return "发送";
                }
            }
        }

        //public Guid LoginGuid { get; set; }

        [RelayCommand]
        public async Task SendSmsAsync()
        {
            if (PhoneNumber != null)
            {
                if (CommonData.Regex_PhoneNumber.IsMatch(PhoneNumber))
                {
                    WaitSeconds = 61;
                    await SendSmsAsync(PhoneNumber);
                    WaitingSms = true;
                    _timer.Start();
                }
            }

        }
        [RelayCommand]
        public async Task BindPhoneNumber()
        {
            var request = new AddProviderRequest
            {
                UserName = PhoneNumber,
                LoginKey = LoginKey,
                ProviderKey = _userContext.WxAppLoginResponse.ProviderKey,
                ProviderName = _userContext.WxAppLoginResponse.LoginProvider,
                SmsCode = SmsCode,
            };
            try
            {
                var result = await _idsService.AddProviderAsync(request);
                if (result != null && result.Code == GlobalErrorCode.Ok)
                {
                    Growl.Success("绑定成功，请重新登登陆");
                    SmsCode = null;
                    PhoneNumber = null;
                    WaitingSms = false;
                    WaitSeconds = 0;
                    _timer.Stop();
                    //给登陆viewmodel 发消息，登陆成功
                    WeakReferenceMessenger.Default.Send(new PropertyChangedMessage<bool>(this, CommonData.BindSuccess, false, true));
                }
                else
                {
                    Growl.Warning(result?.ErroMessage);
                }
            }
            catch (Exception ex)
            {
                Growl.Error(ex.Message);
            }
        }


        private async Task SendSmsAsync(string phoneNumber)
        {
            try
            {
                var result = await _idsService.SendSmsAsync(new SendSmsRequest(phoneNumber, true));
                if (result != null && result.Code == GlobalErrorCode.Ok)
                {
                    Growl.Success("发送成功，请注意查收");
                }
                else
                {
                    Growl.Warning(result?.ErroMessage);
                }
            }
            catch (Exception ex)
            {

                Growl.Error(ex.Message);
            }
        }

        private void Timer_Tick(object? sender, EventArgs e)
        {
            if (WaitSeconds > 0)
            {
                WaitSeconds--;
                //btnSendSms.Content = $"{_waitSecond.ToString("D2")}秒";
                //btnSendSms.IsEnabled = false;
                //tbPhoneNumber.IsEnabled = false;
            }
            else
            {
                WaitingSms = false;
                _timer.Stop();
                //btnSendSms.Content = $"发送";
                //btnSendSms.IsEnabled = true;
                //tbPhoneNumber.IsEnabled = true;
            }
        }
    }
}
